<?php
/**
 * tpshop
 * ============================================================================
 * 版权所有 2015-2027 佛山维亚轩科技，并保留所有权利。
 * 网站地址: http://www.vyxjj.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 */
namespace WXAPI\Controller;
// use Admin\Logic\GoodsLogic;
// use Admin\Controller\PintController;
// use Think\AjaxPage;
use Think\Page;
class PintController extends BaseController {
	//获取所有拼团类型列表
	public function getPintTypeList(){
		$con =  M('config');
		//是否开启了拼团
		$isPint = $con->where(array('name'=>"pint_can"))->getField('value');
		if(!$isPint){
			exit(json_encode(array('isPint'=>0)));
		}
		$this->pint_check_order();
		//banner
		$b = $con->field('value')->where(array('name'=>"pint_images"))->find();
		$ba = explode(',',$b['value']);
		$banner = array();
		foreach($ba as $v){
			$banner[] = SITE_URL.$v;  //轮播图片路径 $banner为一维数组
		}
		$pintimages = M('Ad')->where(array('pid'=>51333,'enabled'=>1))->field('ad_code')->select();
        if (!empty($pintimages)){
            
            foreach ($pintimages as $key => $value) {
                $pintimage[$key] = SITE_URL.$value['ad_code'];
            }
            $banner = $pintimage;
        }else{
            $banner = $banner;
        }
		//cat
	    $rule = $con->field('value')->where(array('name'=>"pint_types"))->find(); // 拼团商品分类ID
	    $types = explode(",",$rule['value']);  // 把商品分类ID放入数组中
	    $cat = array();
	    if(in_array("-1",$types)){
	    	$cat[] = array(
                'id'	=>	'-1',
                'name'	=>	'热销'
            );
	    }
	    //  查询所有顶级分类ID和手机端显示的分类名
	    $name = M('goods_category')->field('id,mobile_name')->where(array('parent_id'=>0))->select();
	    foreach($name as $v){
	    	if(in_array($v['id'],$types)){
	    		$cat[] = array(
                    'id'	=>	$v['id'],
                    'name'	=>	$v['mobile_name']
                );
	    	}
	    }
	    //goods
	    $type = $cat[0]['id'];
	    if($type == -1){
	    	$goods['list'] = M("goods")->field("goods_id,pt_numed,store_id,goods_name,original_img,pt_price,shop_price")
                ->where(array("is_pint"=>1,"pt_hot"=>1,"is_on_sale"=>1))->limit('0,10')->select();  //查找拼团商品
	    	$goods['page'] = 1;
	    	$count = M("goods")->where(array("is_pint"=>1,"pt_hot"=>1,"is_on_sale"=>1))->count();
	    	if($count>10){
	    		$goods['row_count'] = 1;
	    	}else{
	    		$goods['row_count'] = 0;
	    	}
	    }else{
	    	$goods['list'] = M("goods")->field("goods_id,pt_numed,store_id,goods_name,original_img,pt_price,shop_price")
                ->where(array("is_pint"=>1,"cat_id1"=>$type,"is_on_sale"=>1))->limit('0,10')->select();
	    	$goods['page'] = 1;
	    	$count = M("goods")->where(array("is_pint"=>1,"pt_hot"=>1,"is_on_sale"=>1))->count();
	    	if($count>10){
	    		$goods['row_count'] = 1;
	    	}else{
	    		$goods['row_count'] = 0;
	    	}
	    }
	    foreach($goods['list'] as $k=>$v){
	    	$goods['list'][$k]['original_img'] = SITE_URL.$v['original_img'];
	    }
	    $json_arr = array(
			'code'		=>	'0',
	    	'msg'		=>	'success',
    		'banner'	=>	$banner,
    		'cat'		=>	$cat,
    		'goods'		=>	$goods,
    		'isPint'	=>	1,
	    	);
	    exit(json_encode($json_arr));
	}
	//获取一级分类或者热销拼团商品列表
	public function getPintGoodsList(){
	    $type = I("type_id",-1);
	    if($type == -1){
	    	$goods['list'] = M("goods")->field("goods_id,pt_numed,store_id,goods_name,original_img,pt_price,shop_price")->where(array("is_pint"=>1,"pt_hot"=>1,"is_on_sale"=>1))->limit('0,10')->select();
	    	$goods['page'] = 1;
	    	$count = M("goods")->where(array("is_pint"=>1,"pt_hot"=>1,"is_on_sale"=>1))->count();
	    	if($count>10){
	    		$goods['row_count'] = 1;
	    	}else{
	    		$goods['row_count'] = 0;
	    	}
	    }else{
	    	$goods['list'] = M("goods")->field("goods_id,pt_numed,store_id,goods_name,original_img,pt_price,shop_price")->where(array("is_pint"=>1,"cat_id1"=>$type,"is_on_sale"=>1))->limit('0,10')->select();
	    	$goods['page'] = 1;
	    	$count = M("goods")->where(array("is_pint"=>1,"pt_hot"=>1,"is_on_sale"=>1))->count();
	    	if($count>10){
	    		$goods['row_count'] = 1;
	    	}else{
	    		$goods['row_count'] = 0;
	    	}
	    }
	    foreach($goods['list'] as $k=>$v){
	    	$goods['list'][$k]['original_img'] = SITE_URL.$v['original_img'];
	    }
	    $json_arr = array(
			'code'	=>	'0',
	    	'msg'	=>	'success',
    		'goods'	=>	$goods,
	    	);
	    exit(json_encode($json_arr));
	}



	// 获取拼团商品信息
	public function getPintGoodsInfo(){
		$this->pint_check_order();
		$goods_id = I("goods_id");//商品信息
		// var_dump($goods_id);
		//判断是不是拼团商品
		if(!$goods_id){
			echo '没有商品id';
			die;
		}
		$goods = M('goods')->find($goods_id);
		if(!$goods){
			echo '该商品不存在';
			die;
		}
		if(!$goods['is_pint']){
			echo '该商品不是拼团商品';
			die;
		}
		$goods_img = M("goods_images")->where(array("goods_id"=>$goods_id))->select();//商品图片
		$goods_collect = M("goods_collect")->where(array("goods_id"=>$goods_id))->count();//收藏数
	}

	public function pintInfo(){

		$users = M('users');
		$goods_id = I("goods_id");
		$pint = M('pint')->where(array('goods_id'=>$goods_id,'pint_status'=>0))->limit(0,10)->select();
		if(!$pint){
			$json_arr = array(
				'num'	=>	'0'
		    	);
	    	exit(json_encode($json_arr));
		}
		foreach($pint as $k=>$v){
			$pint[$k]['user'] = $users->field("head_pic,nick_name")->find($v['user_id']);
			$time_data=date('Y-m-j-h-i-s',$v['pint_stop_time']);
			$pint[$k]['limit_time_ms']=explode("-", $time_data);
		}
		$json_arr = array(
			'num'	=>	count($pint),
			'data'	=>	$pint
	    	);
	    exit(json_encode($json_arr));
	}

	public function pintList(){
		$user_id = I('user_id',0);
		$page 	 = I('page',0);
		$ctype 	 = I('ctype',0);
		$user = M('users')->find($user_id);
		if(!$user){
			exit(json_encode(array('code'=>0)));
		}
		$this->pint_check_order();
		switch($ctype){
			case 0:
			$sql = "select g.*,gg.original_img,p.*,o.order_id,o.order_amount from ty_order as o,ty_pint as p,ty_order_goods as g,ty_goods as gg where o.user_id = ".$user_id." and o.order_prom_type = 101 and p.pint_id = o.order_prom_id and g.order_id = o.order_id and gg.goods_id = g.goods_id";
			break;
			case 1:
			$sql = "select g.*,gg.original_img,p.*,o.order_id,o.order_amount from ty_order as o,ty_pint as p,ty_order_goods as g,ty_goods as gg where o.user_id = ".$user_id." and o.order_prom_type = 101 and p.pint_id = o.order_prom_id and p.pint_status = 0 and g.order_id = o.order_id and gg.goods_id = g.goods_id";
			break;
			case 2:
			$sql = "select g.*,gg.original_img,p.*,o.order_id,o.order_amount from ty_order as o,ty_pint as p,ty_order_goods as g,ty_goods as gg where o.user_id = ".$user_id." and o.order_prom_type = 101 and p.pint_id = o.order_prom_id and p.pint_status = 1 and g.order_id = o.order_id and gg.goods_id = g.goods_id";
			break;
			case 3:
			$sql = "select g.*,gg.original_img,p.*,o.order_id,o.order_amount from ty_order as o,ty_pint as p,ty_order_goods as g,ty_goods as gg where o.user_id = ".$user_id." and o.order_prom_type = 101 and p.pint_id = o.order_prom_id and p.pint_status = 2 and g.order_id = o.order_id and gg.goods_id = g.goods_id";
			break;
		}
		$pint = M()->query($sql);
		foreach($pint as $k=>$v){
			$pint[$k]['original_img'] = SITE_URL.$v['original_img'];
		}
		exit(json_encode(array('code'=>1,'pint'=>$pint,'length'=>count($pint))));
	}

	//拼团失败删除订单
    public function pint_check_order(){
        $can = M('config')->where(array('name'=>'pint_can'))->getField('value');
        if($can){
            $time = time();
            $pints = M('pint')->where('pint_stop_time <='.$time.' and pint_status=0')->select();
            if($pints){
                $or = M('order');
                M('pint')->where('pint_stop_time <='.$time.' and pint_status=0')->save(array('pint_status'=>2));
                $ids = array();
                foreach($pints as $p){
                    $ids[] = $p['pint_id'];
                }
                $id = implode(',',$ids);
                $orders = $or->where('order_prom_type = 101 and order_prom_id in('.$id.')')->select();

                $ids = '';
                $data = array();
                $time = time();
                foreach ($orders as $k => $v) {
                    //退款退积分退红包退余额
                    //付款全部退还至月，积分全部退还值积分
                    $money = 0;
                    if($v['pay_status'] == 1 && $v['pay_code'] != 'cod'){
                    	$res = $this->weixintuikuan($v['order_id']);
                    	$money += $v['user_money'];
                    	$money += $v['order_amount'];
                    }else if($v['pay_code'] == 'cod' && $v['user_money'] > 0){
                    	$money += $v['user_money'];
                    }
                    if($money > 0){
                        $or->where(array('order_id'=>$v['order_id']))->setInc('user_money',$money);
                    }
                    if($v['integral'] > 0){
                        $or->where(array('order_id'=>$v['order_id']))->setInc('pay_points',$v['integral']);
                    }
                    $ids .= $v['order_id'].',';
                    $data[] = array(
                        'order_id' => $v['order_id'],
                        'action_user' => $v['user_id'],
                        'action_note' => '系统自动取消订单',
                        'order_status' => 3,
                        'log_time' => $time,
                        'status_desc' => '拼团超时,取消订单',
                        );
                }
                $ids = trim($ids,',');
                $or->where("order_id in(".$ids.")")->save(array('order_status'=>3,'pay_status'=>2));
                M('order_action')->addAll($data);//订单操作记录
            }
        }
    }

    public function getPintInfo(){
    	$user_id = I('user_id');
    	$pint_id = I('pint_id');
    	if(!$pint_id){
    		$oid = M('order')->where(array('user_id'=>$user_id))->getField('MAX(order_id)');
    		$pint_id = M('order')->where(array('order_id'=>$oid))->getField('order_prom_id');
    	}
    	$pint = M('pint')->find($pint_id);
    	if(!$pint){
    		exit(json_encode(array('code'=>0)));//拼团不存在
    	}
    	$data['pint'] = $pint;
    	$data['goods'] = M('goods')->find($pint['goods_id']);
    	$data['goods']['original_img'] = SITE_URL.$data['goods']['original_img'];
    	$data['groupList'] = M('users')->where("user_id in(".$pint['users_id'].")")->select();
    	foreach($data['groupList'] as $k=>$v){
    		$data['groupList'][$k]['head_pic'] = $data['groupList'][$k]['head_pic'];
    	}
    	$aaa = array();
    	$users = explode(',',$pint['users_id']);
    	foreach($users as $vv){
    		foreach($data['groupList'] as $k=>$v){
    			if($v['user_id'] == $vv){
    				$aaa[] = $data['groupList'][$k];
    			}
    		}
    	}
    	$data['groupList'] = $aaa;
    	if($pint['pint_status'] == 0){
    		if($pint['pint_stop_time']-time() > 0){
    			$data['limit_time_ms'] = explode(',',date('Y,n,j,H,i,s',$pint['pint_stop_time']));
    		}
    	}
    	$data['goodsList'] = M("goods")->field("goods_id,pt_numed,store_id,goods_name,original_img,pt_price,shop_price")->where(array("is_pint"=>1,"pt_hot"=>1,"is_on_sale"=>1))->limit('0,3')->select();
    	foreach($data['goodsList'] as $k=>$v){
    		$data['goodsList'][$k]['original_img'] = SITE_URL.$data['goodsList'][$k]['original_img'];
    	}
    	$data['surplus'] = $pint['pint_user_num']-$pint['pint_user_num_now'];
    	$data['groupFail'] = $pint['pint_status'];
    	$users = explode(',',$pint['users_id']);
    	if(in_array($user_id,$users)){
			$data['inGroup'] = true;
    	}else{
    		$data['inGroup'] = false;
    	}
    	exit(json_encode($data));
    }

    public function article(){
		$data['code'] = 0;
		$data['data']['title'] = '拼团须知';
		$content = M('config')->where(array('name'=>'pint_rule'))->getField('value');
		$y = 'src="/Public';
		$x = 'src="'.SITE_URL.'/Public';
		$data['data']['content'] = strtr($content,array($y=>$x));
		exit(json_encode($data));
	}

	public function getPintId(){
		$order_id = I('order_id');
		$pint_id = M('order')->where(array('order_id'=>$order_id))->getField('order_prom_id');
		exit(json_encode(array('pint_id'=>$pint_id)));
	}

	public function weixintuikuan($order_id){

		$cert = './plugins/payment/weixin/cert/';
		// $order_id = I('order_id');
		$order = M('order')->find($order_id);
		if(!$order || $order['pay_status'] == 0){
			return 0;
		}
		$paymentPlugin = M('Plugin')->where("code='weixin' and  type = 'payment' ")->find();
        $config_value = unserialize($paymentPlugin['config_value']);

		$data['appid'] = $config_value['appid'];
		$data['mch_id'] = $config_value['mchid'];
		$data['nonce_str'] = $this->getNonceStr();
		$data['out_trade_no'] = $order['master_order_sn'];
		$data['out_refund_no'] = 't'.$order['master_order_sn'];
		$data['total_fee'] = $order['order_amount']*100;
		$data['refund_fee'] = $order['order_amount']*100;
		$key = $config_value['key'];

		$str =  'appid='.$data['appid'].
				'&mch_id='.$data['mch_id'].
				'&nonce_str='.$data['nonce_str'].
				'&out_refund_no='.$data['out_refund_no'].
				'&out_trade_no='.$data['out_trade_no'].
				'&refund_fee='.$data['refund_fee'].
				'&total_fee='.$data['total_fee'].'&key='.$key;
		$data['sign'] = strtoupper(md5($str));

		$xml = $this->arrayToXml($data);
		$url = 'https://api.mch.weixin.qq.com/secapi/pay/refund';
		$curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $xml);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($curl,CURLOPT_SSLCERTTYPE,'PEM');
		curl_setopt($curl,CURLOPT_SSLCERT, $cert.'apiclient_cert.pem');
		curl_setopt($curl,CURLOPT_SSLKEYTYPE,'PEM');
		curl_setopt($curl,CURLOPT_SSLKEY, $cert.'apiclient_key.pem');
        $result = curl_exec($curl);
        
        if (curl_errno($curl)) {
            curl_close($curl);
            return false;
        }
        curl_close($curl);
        return true;
	}

	// 获取指定长度的随机字符串
    function getNonceStr()
    {
    	$length = mt_rand(19,31);
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol) - 1;
    
        for ($i = 0; $i < $length; $i ++) {
            $str .= $strPol[rand(0, $max)]; // rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }
    
        return $str;
    }
    // 数组转xml
    function arrayToXml($arr)
    {
        
        $xml = "<xml>";
        
        foreach ($arr as $key => $val) {
            // if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            // } else {
                // $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            // }
        }
        $xml .= "</xml>";
        
        
        return $xml;
    }
    public function xmlToArray($xml){ 
		//禁止引用外部xml实体 
		libxml_disable_entity_loader(true); 
		$xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA); 
		$val = json_decode(json_encode($xmlstring),true); 
		return $val; 
	} 
}